<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
          <el-button link type="primary" @click="toggleFilterExpand">
            {{ filterExpanded ? '收起' : '展开' }}
            <el-icon>
              <ArrowDown v-if="!filterExpanded" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>
      </template>

      <div class="filter-container" :class="{ 'filter-collapsed': !filterExpanded }">
        <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
          <el-form-item label="用户名">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><Avatar /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @clear="handleQuery">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons-container">
            <div class="search-buttons">
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
        </div>
      </template>

      <div class="table-container">
        <div class="table-toolbar">
          <div class="left-buttons">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增用户</el-button>
          </div>
        </div>

        <el-table 
          v-loading="loading" 
          :data="userList" 
          size="default"
          border 
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="user_name" label="用户名" min-width="120" />
          <el-table-column prop="real_name" label="姓名" min-width="120" />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column label="角色" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.role === 1" type="danger" effect="plain">管理员</el-tag>
              <el-tag v-else type="info" effect="plain">普通用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="(val) => handleStatusChange(scope.row, val)"
                :loading="scope.row.statusLoading"
                :disabled="scope.row.id === userStore.userId"
              />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="160" show-overflow-tooltip>
            <template #default="scope">
              {{ formatDateTime(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="scope">
              <div class="table-operation-buttons">
                <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="warning" link :icon="Key" @click="handleChangePassword(scope.row)">修改密码</el-button>
                <el-button type="success" link :icon="RefreshRight" @click="handleResetPassword(scope.row)">重置密码</el-button>
                <el-popconfirm
                  :title="`确认删除用户 ${scope.row.user_name} 吗?`"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="handleDelete(scope.row)"
                  v-if="scope.row.id !== userStore.userId"
                >
                  <template #reference>
                    <el-button type="danger" link :icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="550px" 
      destroy-on-close
      center
      align-center
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="80px" status-icon>
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="userForm.user_name" placeholder="请输入用户名" :disabled="dialogType === 'edit'">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="userForm.real_name" placeholder="请输入姓名">
            <template #prefix>
              <el-icon><Avatar /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" :value="1" />
            <el-option label="普通用户" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      destroy-on-close
      append-to-body
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 重置密码结果对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="密码重置成功"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="reset-password-container">
        <el-alert
          title="请记住以下密码，关闭后将无法再次查看！"
          type="warning"
          :closable="false"
          show-icon
        />
        <div class="reset-password-info">
          <p><strong>用户名：</strong>{{ resetPasswordInfo.username }}</p>
          <p><strong>新密码：</strong>{{ resetPasswordInfo.password }}</p>
        </div>
        <div class="copy-password">
          <el-button type="primary" @click="copyResetPassword">复制密码</el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="resetPasswordDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, Refresh, ArrowDown, ArrowUp,
  User, Avatar, Lock, Message, Key, RefreshRight
} from '@element-plus/icons-vue'
import { getUsers, getUser, createUser, updateUser, deleteUser, changePassword, resetPassword } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { validEmail } from '@/utils/validate'

const userStore = useUserStore()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  realName: '',
  status: null
})

// 表单对象
const userForm = reactive({
  id: undefined,
  user_name: '',
  real_name: '',
  email: '',
  password: '',
  role: 0,
  status: 1,
  version: 1
})

// 表单校验规则
const userRules = {
  user_name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  real_name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value && !validEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  role: [{ required: true, message: '角色不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
}

// 数据列表
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // 'add' 或 'edit'
const userFormRef = ref()
const submitLoading = ref(false)

// 修改密码对话框相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref()
const passwordForm = reactive({
  id: undefined,
  username: '',
  password: '',
  confirmPassword: '',
  version: 1
})

// 重置密码对话框相关
const resetPasswordDialogVisible = ref(false)
const resetPasswordInfo = reactive({
  username: '',
  password: ''
})

// 密码表单校验规则
const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// UI控制变量
const filterExpanded = ref(true)

// 切换筛选器展开/收起
const toggleFilterExpand = () => {
  filterExpanded.value = !filterExpanded.value
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const params = {
      skip: (queryParams.pageNum - 1) * queryParams.pageSize,
      limit: queryParams.pageSize,
      username: queryParams.username.trim() || undefined,
      realName: queryParams.realName.trim() || undefined,
      status: queryParams.status === null ? undefined : queryParams.status
    }
    
    const res = await getUsers(params)
    userList.value = res.data?.map(user => ({
      ...user,
      statusLoading: false
    })) || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getUserList()
}

// 重置查询
const resetQuery = () => {
  queryParams.username = ''
  queryParams.realName = ''
  queryParams.status = null
  queryParams.pageNum = 1
  getUserList()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getUserList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getUserList()
}

// 添加用户
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加用户'
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  resetForm()
  dialogTitle.value = '编辑用户'
  dialogType.value = 'edit'
  
  try {
    const res = await getUser(row.id)
    Object.assign(userForm, res.data)
    userForm.password = '' // 编辑时不显示密码
    
    // 更新表单校验规则，编辑时密码不是必填项
    if (userRules.password && userRules.password.length > 0) {
      userRules.password[0].required = false
    }
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 处理状态变化
const handleStatusChange = async (row, status) => {
  // 如果是当前用户，禁止修改状态
  if (row.id === userStore.userId) {
    ElMessage.warning('不能修改当前登录账户的状态')
    return
  }
  
  // 设置状态加载中
  const userIndex = userList.value.findIndex(u => u.id === row.id)
  if (userIndex >= 0) {
    userList.value[userIndex].statusLoading = true
  }
  
  try {
    await updateUser(row.id, {
      status,
      version: row.version
    })
    
    const statusText = status === 1 ? '启用' : '禁用'
    ElMessage.success(`${statusText}成功`)
    
    // 更新版本号
    if (userIndex >= 0) {
      userList.value[userIndex].version += 1
    }
  } catch (error) {
    console.error(`修改用户状态失败:`, error)
    ElMessage.error(`修改用户状态失败`)
    
    // 恢复原状态
    if (userIndex >= 0) {
      userList.value[userIndex].status = status === 1 ? 0 : 1
    }
  } finally {
    // 移除状态加载中
    if (userIndex >= 0) {
      userList.value[userIndex].statusLoading = false
    }
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除用户失败')
  }
}

// 处理修改密码
const handleChangePassword = (row) => {
  passwordForm.id = row.id
  passwordForm.username = row.user_name
  passwordForm.version = row.version
  passwordForm.password = ''
  passwordForm.confirmPassword = ''
  
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  
  passwordDialogVisible.value = true
}

// 提交密码表单
const submitPasswordForm = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 只更新密码字段
        await updateUser(passwordForm.id, {
          password: passwordForm.password,
          version: passwordForm.version
        })
        
        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false
        
        // 刷新用户列表，获取最新版本号
        getUserList()
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 处理重置密码
const handleResetPassword = async (row) => {
  try {
    submitLoading.value = true
    const res = await resetPassword(row.id)
    
    // 显示重置后的密码
    resetPasswordInfo.username = row.user_name
    resetPasswordInfo.password = res.data.password
    
    resetPasswordDialogVisible.value = true
    
    // 刷新用户列表，获取最新版本号
    getUserList()
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置密码失败: ' + (error.message || '未知错误'))
  } finally {
    submitLoading.value = false
  }
}

// 复制重置后的密码
const copyResetPassword = () => {
  try {
    navigator.clipboard.writeText(resetPasswordInfo.password)
    ElMessage.success('密码已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 重置表单
const resetForm = () => {
  userForm.id = undefined
  userForm.user_name = ''
  userForm.real_name = ''
  userForm.email = ''
  userForm.password = ''
  userForm.role = 0
  userForm.status = 1
  userForm.version = 1
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  
  // 恢复密码校验规则
  if (userRules.password && userRules.password.length > 0) {
    userRules.password[0].required = true
  }
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 检查是否在编辑当前登录用户并且尝试禁用自己
      if (dialogType.value === 'edit' && userForm.id === userStore.userId && userForm.status === 0) {
        ElMessage.warning('不能禁用当前登录账户')
        return
      }
      
      submitLoading.value = true
      try {
        if (dialogType.value === 'edit') {
          // 编辑
          const updateData = { ...userForm }
          
          // 如果密码为空，不更新密码
          if (!updateData.password) {
            delete updateData.password
          }
          
          await updateUser(userForm.id, updateData)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await createUser(userForm)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        getUserList()
      } catch (error) {
        console.error('保存用户信息失败:', error)
        ElMessage.error('保存用户信息失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
  max-height: 300px;
  overflow: hidden;
  opacity: 1;
  
  &.filter-collapsed {
    max-height: 0;
    opacity: 0;
  }
}

.table-operation-buttons {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  gap: 5px;
  
  .el-button {
    margin: 0;
  }
}
</style>